package modulos.usuario.vista;

import basedatos.OperacionesBD;
import basedatos.UsuarioBD;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
import modelo.Persona;
import modulos.usuario.modelo.Cuenta_Usuario;
import modulos.usuario.modelo.Usuario;
import vista.modelo.OperacionesVarias;

/**
 *
 * @author caesar
 */
public class iFrmUsuario extends javax.swing.JInternalFrame {
    
    Cuenta_Usuario eCuenta_usuario = new Cuenta_Usuario();
    Persona ePersona = new Persona();
    //usados para la busqueda
    Cuenta_Usuario findCuenta_Usuario;
    Usuario findUsuario;
    Persona findPersona;
    
    //Tipos de Usuario
    public static final String TIPO_MEDICO="MEDICO";
    public static final String TIPO_ASISTENTE="ASISTENTE";
    public static final String TIPO_ADMIN="ADMINISTRADOR";
    
    public iFrmUsuario() {
        initComponents();
        cmbTipoUsuario.addItem(TIPO_ADMIN);
        cmbTipoUsuario.addItem(TIPO_MEDICO);
        cmbTipoUsuario.addItem(TIPO_ASISTENTE);
        OperacionesVarias.cerrarVentanaEscape(this);
        lbltxtIdUsuario.setVisible(false);
        setNuevoUsuario();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlId = new javax.swing.JPanel();
        txtApellido = new javax.swing.JTextField();
        lblCedula = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        lbltxtIdUsuario = new javax.swing.JLabel();
        txtCedula = new javax.swing.JTextField();
        pnlPermiso = new javax.swing.JPanel();
        cmbTipoUsuario = new javax.swing.JComboBox();
        lblTipoUsuario = new javax.swing.JLabel();
        pnlAcceso = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtReClave = new javax.swing.JPasswordField();
        chkAsignar = new javax.swing.JCheckBox();
        txtClave = new javax.swing.JPasswordField();
        chkModificar = new javax.swing.JCheckBox();
        jPanel1 = new javax.swing.JPanel();
        btnNuevo = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnCerrar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Usuario");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/usuario.png"))); // NOI18N
        setPreferredSize(new java.awt.Dimension(460, 520));
        setVisible(true);
        getContentPane().setLayout(null);

        pnlId.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED), "Identificación:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, null, null));

        txtApellido.setBackground(new java.awt.Color(254, 237, 214));
        txtApellido.setEditable(false);
        txtApellido.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtApellidoKeyReleased(evt);
            }
        });

        lblCedula.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        lblCedula.setText("Cédula:");

        jLabel1.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        jLabel1.setText("Nombre:");

        jLabel2.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        jLabel2.setText("Apellido:");

        txtNombre.setBackground(new java.awt.Color(254, 237, 214));
        txtNombre.setEditable(false);
        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNombreKeyReleased(evt);
            }
        });

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/search.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        lbltxtIdUsuario.setFocusable(false);

        txtCedula.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCedulaKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCedulaKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout pnlIdLayout = new javax.swing.GroupLayout(pnlId);
        pnlId.setLayout(pnlIdLayout);
        pnlIdLayout.setHorizontalGroup(
            pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlIdLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlIdLayout.createSequentialGroup()
                        .addGroup(pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblCedula, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(pnlIdLayout.createSequentialGroup()
                                .addGroup(pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lbltxtIdUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(pnlIdLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(txtNombre)))
                .addContainerGap(49, Short.MAX_VALUE))
        );
        pnlIdLayout.setVerticalGroup(
            pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlIdLayout.createSequentialGroup()
                .addComponent(lbltxtIdUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCedula)
                    .addComponent(btnBuscar)
                    .addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlIdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33))
        );

        getContentPane().add(pnlId);
        pnlId.setBounds(12, 12, 412, 161);

        pnlPermiso.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED), "Seguridad: ", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, null, null));

        cmbTipoUsuario.setEnabled(false);

        lblTipoUsuario.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        lblTipoUsuario.setText("Permisos de usuario:");

        javax.swing.GroupLayout pnlPermisoLayout = new javax.swing.GroupLayout(pnlPermiso);
        pnlPermiso.setLayout(pnlPermisoLayout);
        pnlPermisoLayout.setHorizontalGroup(
            pnlPermisoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlPermisoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTipoUsuario)
                .addGap(26, 26, 26)
                .addComponent(cmbTipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(45, Short.MAX_VALUE))
        );
        pnlPermisoLayout.setVerticalGroup(
            pnlPermisoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlPermisoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pnlPermisoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbTipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTipoUsuario))
                .addGap(128, 128, 128))
        );

        getContentPane().add(pnlPermiso);
        pnlPermiso.setBounds(12, 183, 412, 68);

        pnlAcceso.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Datos de acceso:", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, null, null));

        jLabel3.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        jLabel3.setText("Usuario:");

        txtUsuario.setEnabled(false);
        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyReleased(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        jLabel4.setText("Contraseña:");

        jLabel5.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        jLabel5.setText("Confirmar:");

        txtReClave.setEnabled(false);
        txtReClave.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtReClaveKeyReleased(evt);
            }
        });

        chkAsignar.setText("Asignar");
        chkAsignar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkAsignarActionPerformed(evt);
            }
        });

        txtClave.setEnabled(false);
        txtClave.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtClaveKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout pnlAccesoLayout = new javax.swing.GroupLayout(pnlAcceso);
        pnlAcceso.setLayout(pnlAccesoLayout);
        pnlAccesoLayout.setHorizontalGroup(
            pnlAccesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlAccesoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlAccesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(chkAsignar)
                    .addGroup(pnlAccesoLayout.createSequentialGroup()
                        .addGroup(pnlAccesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(pnlAccesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtReClave, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtClave, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(47, Short.MAX_VALUE))
        );
        pnlAccesoLayout.setVerticalGroup(
            pnlAccesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlAccesoLayout.createSequentialGroup()
                .addComponent(chkAsignar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pnlAccesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlAccesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlAccesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtReClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        getContentPane().add(pnlAcceso);
        pnlAcceso.setBounds(12, 257, 419, 158);

        chkModificar.setText("Modificar seguridad");
        chkModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkModificarActionPerformed(evt);
            }
        });
        getContentPane().add(chkModificar);
        chkModificar.setBounds(277, 420, 148, 22);

        jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        btnNuevo.setFont(new java.awt.Font("Ubuntu", 0, 13)); // NOI18N
        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/add.png"))); // NOI18N
        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnGuardar.setFont(new java.awt.Font("Ubuntu", 0, 13)); // NOI18N
        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/filesave.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnEliminar.setFont(new java.awt.Font("Ubuntu", 0, 13)); // NOI18N
        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/delete.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnCerrar.setFont(new java.awt.Font("Ubuntu", 0, 13)); // NOI18N
        btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/agt_home.png"))); // NOI18N
        btnCerrar.setText("Cerrar");
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addComponent(btnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNuevo)
                    .addComponent(btnGuardar)
                    .addComponent(btnCerrar)
                    .addComponent(btnEliminar))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1);
        jPanel1.setBounds(10, 450, 420, 30);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private Usuario getEntidadUsuario() {
        Usuario u = new Usuario();
        u.setNombre(txtNombre.getText().trim());
        u.setApellido(txtApellido.getText().trim());
        u.setCedula(txtCedula.getText().trim());
        return u;
    }
    
    private Cuenta_Usuario getEntidadCtaUsuario() {
        Cuenta_Usuario cu = new Cuenta_Usuario();
        if (btnGuardar.getText().trim().compareTo("Actualizar".trim()) == 0) {
            cu.setId(findCuenta_Usuario.getId());
        }
        cu.setNomUsuario(txtUsuario.getText().trim());
        cu.setClave(txtClave.getText().trim());
        cu.setEstado("A");
        cu.setTipo(cmbTipoUsuario.getSelectedItem().toString());
        return cu;
    }
    
    private void setNuevoUsuario() {
        btnGuardar.setText("Guardar".trim());
        txtCedula.setEditable(true);
        txtNombre.setEditable(true);
        txtApellido.setEditable(true);
        
        txtCedula.setText("");
        txtNombre.setText("");
        txtApellido.setText("");
        txtUsuario.setText("");
        txtClave.setText("");
        txtReClave.setText("");
        
        txtClave.setEditable(true);
        cmbTipoUsuario.setSelectedIndex(-1);
        cmbTipoUsuario.setEnabled(true);
        
        chkAsignar.setEnabled(true);
        chkModificar.setVisible(false);
        chkModificar.setSelected(false);
        
        findCuenta_Usuario = null;
        findUsuario = null;
        findPersona = null;
        txtCedula.requestFocus();
    }
    
    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed
    
    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        setNuevoUsuario();
    }//GEN-LAST:event_btnNuevoActionPerformed
    
    @SuppressWarnings("static-access")
    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        try {
            if (txtCedula.getText().trim().length() == 0 || txtNombre.getText().trim().length() == 0 || txtApellido.getText().trim().length() == 0 || txtUsuario.getText().trim().length() == 0 || cmbTipoUsuario.getSelectedIndex() == -1) {
                JOptionPane.showMessageDialog(null, "Los campos Cédula, Nombre, Usuario y Permisos son obligatorios ...", "Guardar", JOptionPane.WARNING_MESSAGE);
                return;
            } else if (ePersona.validadorDeCedula(txtCedula.getText().trim()) == false) {
                JOptionPane.showMessageDialog(null, "Número de cédula no válido \nReingrese nuevamente el número...", "Guardar", JOptionPane.WARNING_MESSAGE);
                return;
            } else if (txtClave.getText().trim().compareTo(txtReClave.getText().trim()) != 0) {
                JOptionPane.showMessageDialog(null, "La clave de usuario y su confirmación no coinciden ...", "Guardar", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            if (btnGuardar.getText().compareTo("Guardar".trim()) == 0) {
                if (tieneDuplicado("0", txtCedula.getText().trim(), txtUsuario.getText().trim(), 0) != null) {
                    return;//el 0 se utiliza cuando es insert, >0 cuando es update
                }
            } else {
                if (tieneDuplicado(String.valueOf(findUsuario.getIdPersona()), txtCedula.getText().trim(), txtUsuario.getText().trim(), findCuenta_Usuario.getId()) != null) {
                    return;
                }
            }
            
            if (txtClave.getPassword().length == 0 && txtReClave.getPassword().length == 0)//////
            {
                if (JOptionPane.showConfirmDialog(null, "No ha ingresado la clave de usuario. \nSe recomienda que todo usuario tenga contraseña,\n¿Desea continuar de todas maneras?", "Guardar", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                    if (btnGuardar.getText().compareTo("Guardar".trim()) == 0) {
                        if (eCuenta_usuario.insertUsuario(this.getEntidadUsuario(), this.getEntidadCtaUsuario())) {
                            if (buscarUsuario(null, txtUsuario.getText().trim()) == "OK".trim()) {
                               
                                JOptionPane.showMessageDialog(null, "Datos de usuario guardados correctamente...", "Guardar", JOptionPane.INFORMATION_MESSAGE);
                            }
                        } else {
                            JOptionPane.showMessageDialog(null, "Los datos no se han podido guardar ...", "Guardar", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {//esnuevo= false
                        if (eCuenta_usuario.updatetUsuario(this.getEntidadCtaUsuario())) {
                            if (buscarUsuario(null, txtUsuario.getText().trim()) == "OK".trim()) {
                                JOptionPane.showMessageDialog(null, "Datos de usuario actualizados correctamente...", "Actualizar", JOptionPane.INFORMATION_MESSAGE);
                            }
                        } else {
                            JOptionPane.showMessageDialog(null, "Los datos no se han podido actualizar ...", "Actualizar", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            } else//con clave
            {
                if (eCuenta_usuario.insertUsuario(this.getEntidadUsuario(), this.getEntidadCtaUsuario())) {
                    JOptionPane.showMessageDialog(null, "Datos de usuario guardados correctamente...", "Guardar", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "Los datos no se han podido guardar ...", "Guardar", JOptionPane.ERROR_MESSAGE);
                }
            }
            
        } catch (Exception ex) {
            ex.getMessage();
        }
    }//GEN-LAST:event_btnGuardarActionPerformed
    
    private String tieneDuplicado(String idPersn, String cedula, String usuario, int idCta) {
        String doble = null;
        doble = eCuenta_usuario.validarAtributoDuplicado(Integer.parseInt(idPersn), cedula.trim(), usuario.trim(), idCta);
        if (doble == "c") {
            JOptionPane.showMessageDialog(null, "El numero de cedula " + txtCedula.getText() + " ya existe en la base de datos ... \n Ingrese un numero válido", "Guardar", JOptionPane.WARNING_MESSAGE);
            return doble;
        } else if (doble == "u") {
            JOptionPane.showMessageDialog(null, "El usuario " + txtUsuario.getText() + " ya existe en la base de datos ... \n Ingrese un nombre válido", "Guardar", JOptionPane.WARNING_MESSAGE);
            return doble;
        }
        return doble;//null si no hay atributos duplicados
    }
    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        try {
            List ls = null;
            UsuarioBD ubd = new UsuarioBD();
            ls = eCuenta_usuario.selectUsuario();
            int i = 0;
            Object[] fi = new Object[ubd.getManager()];
            for (Cuenta_Usuario ctaU : (List<Cuenta_Usuario>) ls) {
                fi[i] = ctaU.getNomUsuario();
                i += 1;
            }
            String buscado = (String) JOptionPane.showInputDialog(this, "Seleccione el nombre de 'usuario'", "Buscar", JOptionPane.INFORMATION_MESSAGE, null, fi, fi[0]);
            if (!buscado.equalsIgnoreCase(null));
            buscarUsuario(null, String.valueOf(buscado));//Busca x nombre de usuario. (cedula, usuario)
        } catch (Exception ex) {
            ex.getMessage();
        }
    }//GEN-LAST:event_btnBuscarActionPerformed
    
    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        Cuenta_Usuario cu = new Cuenta_Usuario();
        try {
            if (txtCedula.getText().trim().length() != 0) {
                if (txtCedula.getText().trim().compareTo("0000000000") == 0) {
                    JOptionPane.showMessageDialog(null, "El usuario administrador principal no puede ser eliminado", "Eliminar", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                if (JOptionPane.showConfirmDialog(null, "¿Está seguro de eliminar el usuario seleccionado?", "Eliminar", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                    if (OperacionesBD.eliminar(findCuenta_Usuario)) {
                        JOptionPane.showMessageDialog(null, "Usuario eliminado correctamente...", "Eliminar", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(null, "Los datos del usuario no se han podido eliminar", "Eliminar", JOptionPane.WARNING_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Primero debe buscar un usuario ...", "Eliminar", JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception ex) {
            ex.getMessage();
        }
    }//GEN-LAST:event_btnEliminarActionPerformed
    
    private void chkAsignarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkAsignarActionPerformed
        if (chkAsignar.isSelected()) {
            txtUsuario.setEnabled(true);
            txtClave.setEnabled(true);
            txtReClave.setEnabled(true);
            txtUsuario.setSelectionStart(0);
            txtUsuario.setSelectionEnd(txtUsuario.getText().trim().length());
            txtUsuario.requestFocus();
        } else {
            txtUsuario.setEnabled(false);
            txtClave.setEnabled(false);
            txtReClave.setEnabled(false);
        }
    }//GEN-LAST:event_chkAsignarActionPerformed
    
    private void chkModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkModificarActionPerformed
        if (chkModificar.isSelected()) {
            if (txtCedula.getText().trim().compareTo("0000000000".trim()) != 0)//10 ceros cedula de usr admin x defecto
            {
                cmbTipoUsuario.setEnabled(true);
            }
            chkAsignar.setEnabled(true);
            
        } else {
            cmbTipoUsuario.setEnabled(false);
            chkAsignar.setEnabled(false);
        }
    }//GEN-LAST:event_chkModificarActionPerformed
    
    private void txtNombreKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyReleased
        if (evt.getKeyCode() == 10) {
            txtApellido.requestFocus();
        }
    }//GEN-LAST:event_txtNombreKeyReleased
    
    private void txtApellidoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtApellidoKeyReleased
        if (evt.getKeyCode() == 10) {
            cmbTipoUsuario.requestFocus();
        }
    }//GEN-LAST:event_txtApellidoKeyReleased
    
    private void txtUsuarioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyReleased
        if (evt.getKeyCode() == 10) {
            txtClave.requestFocus();
        }
    }//GEN-LAST:event_txtUsuarioKeyReleased
    
    private void txtClaveKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtClaveKeyReleased
        if (evt.getKeyCode() == 10) {
            txtReClave.requestFocus();
        }
    }//GEN-LAST:event_txtClaveKeyReleased
    
    private void txtReClaveKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtReClaveKeyReleased
        if (evt.getKeyCode() == 10) {
            btnGuardar.requestFocus();
        }
    }//GEN-LAST:event_txtReClaveKeyReleased
    
    private void txtCedulaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCedulaKeyTyped
        
        OperacionesVarias.ingresoNumCedula(evt, txtCedula.getText());
        
    }//GEN-LAST:event_txtCedulaKeyTyped
    
    private void txtCedulaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCedulaKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_A) {
            txtNombre.requestFocus();
        }
        txtUsuario.setText(txtCedula.getText());
    }//GEN-LAST:event_txtCedulaKeyReleased
    
    private String buscarUsuario(String cedula, String usuario) {//Busca x cedula "o" x usuario
        List<Object[]> obj = null;
        String encontrado = null;
        try {
            if (usuario != null) {
                obj = eCuenta_usuario.selectAtributosUsuario(usuario);
            } else if (cedula != null) {
                obj = eCuenta_usuario.selectAtributosUsuario(cedula);
            }
            if (obj.size() > 0) {
                for (Object[] o : obj) {
                    findCuenta_Usuario = (Cuenta_Usuario) o[0];
                    findUsuario = (Usuario) o[1];
                    findPersona = (Persona) o[2];
                    lbltxtIdUsuario.setText(String.valueOf(findCuenta_Usuario.getId()));
                    txtCedula.setText(findUsuario.getCedula());
                    txtNombre.setText(findPersona.getNombre());
                    txtApellido.setText(findPersona.getApellido());
                    txtUsuario.setText(findCuenta_Usuario.getNomUsuario());
                    cmbTipoUsuario.setSelectedItem(findCuenta_Usuario.getTipo());
                    ////////////////////////////
                    txtCedula.setEditable(false);//
                    txtNombre.setEditable(false);
                    txtApellido.setEditable(false);
                    cmbTipoUsuario.setEnabled(false);//
                    txtUsuario.setEnabled(false);//
                    txtClave.setEnabled(false);
                    txtReClave.setEnabled(false);
                    
                    chkAsignar.setEnabled(false);
                    chkAsignar.setSelected(false);
                    
                    chkModificar.setVisible(true);
                    chkModificar.setSelected(false);
                    btnGuardar.setText("Actualizar".trim());
                    encontrado = "OK";
                }
            } else {
                obj = null;
                setNuevoUsuario();
                JOptionPane.showMessageDialog(null, "Los datos del usuario solicitado no existen ...", "Buscar", JOptionPane.WARNING_MESSAGE);
                encontrado = null;
            }
        } catch (Exception ex) {
            ex.getMessage();
            return null;
        }
        return encontrado;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JCheckBox chkAsignar;
    private javax.swing.JCheckBox chkModificar;
    private javax.swing.JComboBox cmbTipoUsuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblCedula;
    private javax.swing.JLabel lblTipoUsuario;
    private javax.swing.JLabel lbltxtIdUsuario;
    private javax.swing.JPanel pnlAcceso;
    private javax.swing.JPanel pnlId;
    private javax.swing.JPanel pnlPermiso;
    private javax.swing.JTextField txtApellido;
    private javax.swing.JTextField txtCedula;
    private javax.swing.JPasswordField txtClave;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JPasswordField txtReClave;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
